import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'dart:io';
import 'dart:typed_data';
import 'ui_enhanced_widgets.dart';

/// 图片选择器服务
/// 封装image_picker，提供统一的图片选择体验
class ImagePickerService {
  static final ImagePicker _picker = ImagePicker();

  /// 从相册选择单张图片
  static Future<XFile?> pickImageFromGallery({
    double? maxWidth,
    double? maxHeight,
    int? imageQuality,
    CameraDevice preferredCameraDevice = CameraDevice.rear,
    bool requestFullMetadata = true,
  }) async {
    try {
      return await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
        preferredCameraDevice: preferredCameraDevice,
        requestFullMetadata: requestFullMetadata,
      );
    } catch (e) {
      SmartDialogs.showError(message: '选择图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 从相机拍摄图片
  static Future<XFile?> pickImageFromCamera({
    double? maxWidth,
    double? maxHeight,
    int? imageQuality,
    CameraDevice preferredCameraDevice = CameraDevice.rear,
    bool requestFullMetadata = true,
  }) async {
    try {
      return await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
        preferredCameraDevice: preferredCameraDevice,
        requestFullMetadata: requestFullMetadata,
      );
    } catch (e) {
      SmartDialogs.showError(message: '拍摄图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 从相册选择多张图片
  static Future<List<XFile>?> pickMultipleImages({
    double? maxWidth,
    double? maxHeight,
    int? imageQuality,
    bool requestFullMetadata = true,
    int? limit,
  }) async {
    try {
      return await _picker.pickMultiImage(
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
        requestFullMetadata: requestFullMetadata,
        limit: limit,
      );
    } catch (e) {
      SmartDialogs.showError(message: '选择图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 选择视频
  static Future<XFile?> pickVideo({
    ImageSource source = ImageSource.gallery,
    CameraDevice preferredCameraDevice = CameraDevice.rear,
    Duration? maxDuration,
  }) async {
    try {
      return await _picker.pickVideo(
        source: source,
        preferredCameraDevice: preferredCameraDevice,
        maxDuration: maxDuration,
      );
    } catch (e) {
      SmartDialogs.showError(message: '选择视频失败: ${e.toString()}');
      return null;
    }
  }

  /// 显示图片选择底部菜单
  static Future<XFile?> showImagePickerSheet(
    BuildContext context, {
    double? maxWidth,
    double? maxHeight,
    int? imageQuality,
    bool enableCrop = true,
  }) async {
    return await showModalBottomSheet<XFile>(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 8),
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.outline.withOpacity(0.3),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 16),
            ListTile(
              leading: const Icon(Icons.camera_alt),
              title: const Text('拍摄照片'),
              onTap: () async {
                Navigator.pop(context);
                final image = await pickImageFromCamera(
                  maxWidth: maxWidth,
                  maxHeight: maxHeight,
                  imageQuality: imageQuality,
                );
                if (image != null && enableCrop && context.mounted) {
                  final croppedImage = await ImageCropperService.cropImage(
                    context,
                    imagePath: image.path,
                  );
                  Navigator.pop(context, croppedImage != null ? XFile(croppedImage.path) : image);
                } else {
                  Navigator.pop(context, image);
                }
              },
            ),
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: const Text('从相册选择'),
              onTap: () async {
                Navigator.pop(context);
                final image = await pickImageFromGallery(
                  maxWidth: maxWidth,
                  maxHeight: maxHeight,
                  imageQuality: imageQuality,
                );
                if (image != null && enableCrop && context.mounted) {
                  final croppedImage = await ImageCropperService.cropImage(
                    context,
                    imagePath: image.path,
                  );
                  Navigator.pop(context, croppedImage != null ? XFile(croppedImage.path) : image);
                } else {
                  Navigator.pop(context, image);
                }
              },
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }
}

/// 图片裁剪服务
/// 封装image_cropper，提供统一的图片裁剪体验
class ImageCropperService {
  
  /// 裁剪图片
  static Future<CroppedFile?> cropImage(
    BuildContext context, {
    required String imagePath,
    CropAspectRatio? aspectRatio,
    List<CropAspectRatioPreset> aspectRatioPresets = const [
      CropAspectRatioPreset.original,
      CropAspectRatioPreset.square,
      CropAspectRatioPreset.ratio3x2,
      CropAspectRatioPreset.ratio4x3,
      CropAspectRatioPreset.ratio16x9
    ],
    int maxWidth = 1080,
    int maxHeight = 1080,
    int compressQuality = 90,
    CropStyle cropStyle = CropStyle.rectangle,
  }) async {
    try {
      return await ImageCropper().cropImage(
        sourcePath: imagePath,
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: '裁剪图片',
            toolbarColor: Theme.of(context).colorScheme.primary,
            toolbarWidgetColor: Theme.of(context).colorScheme.onPrimary,
            backgroundColor: Theme.of(context).colorScheme.surface,
            activeControlsWidgetColor: Theme.of(context).colorScheme.primary,
            dimmedLayerColor: Theme.of(context).colorScheme.scrim.withOpacity(0.5),
            cropFrameColor: Theme.of(context).colorScheme.primary,
            cropGridColor: Theme.of(context).colorScheme.outline,
            statusBarColor: Theme.of(context).colorScheme.primary,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false,
          ),
          IOSUiSettings(
            title: '裁剪图片',
            doneButtonTitle: '完成',
            cancelButtonTitle: '取消',
            aspectRatioLockEnabled: false,
            resetAspectRatioEnabled: true,
            rotateButtonsHidden: false,
            rotateClockwiseButtonHidden: false,
          ),
        ],
      );
    } catch (e) {
      SmartDialogs.showError(message: '裁剪图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 圆形头像裁剪
  static Future<CroppedFile?> cropAvatar(
    BuildContext context, {
    required String imagePath,
    int maxWidth = 512,
    int maxHeight = 512,
    int compressQuality = 90,
  }) async {
    return await cropImage(
      context,
      imagePath: imagePath,
      aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
      aspectRatioPresets: [CropAspectRatioPreset.square],
      maxWidth: maxWidth,
      maxHeight: maxHeight,
      compressQuality: compressQuality,
      cropStyle: CropStyle.circle,
    );
  }
}

/// 图片压缩服务
/// 封装flutter_image_compress，提供统一的图片压缩体验
class ImageCompressService {
  
  /// 压缩图片文件
  static Future<XFile?> compressFile(
    String filePath, {
    int quality = 80,
    int? minWidth,
    int? minHeight,
    int? maxWidth,
    int? maxHeight,
    bool keepExif = false,
    CompressFormat format = CompressFormat.jpeg,
    int rotate = 0,
    bool autoCorrectionAngle = true,
  }) async {
    try {
      final result = await FlutterImageCompress.compressWithFile(
        filePath,
        quality: quality,
        minWidth: minWidth ?? 300,
        minHeight: minHeight ?? 300,
        keepExif: keepExif,
        format: format,
        rotate: rotate,
        autoCorrectionAngle: autoCorrectionAngle,
      );
      
      if (result != null) {
        // 创建临时文件
        final tempFile = File('${filePath}_compressed.jpg');
        await tempFile.writeAsBytes(result);
        return XFile(tempFile.path);
      }
      return null;
    } catch (e) {
      SmartDialogs.showError(message: '压缩图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 压缩图片数据
  static Future<Uint8List?> compressBytes(
    Uint8List bytes, {
    int quality = 80,
    int? minWidth,
    int? minHeight,
    int? maxWidth,
    int? maxHeight,
    bool keepExif = false,
    CompressFormat format = CompressFormat.jpeg,
    int rotate = 0,
    bool autoCorrectionAngle = true,
  }) async {
    try {
      return await FlutterImageCompress.compressWithList(
        bytes,
        quality: quality,
        minWidth: minWidth ?? 300,
        minHeight: minHeight ?? 300,
        keepExif: keepExif,
        format: format,
        rotate: rotate,
        autoCorrectionAngle: autoCorrectionAngle,
      );
    } catch (e) {
      SmartDialogs.showError(message: '压缩图片失败: ${e.toString()}');
      return null;
    }
  }

  /// 批量压缩图片
  static Future<List<XFile>> compressMultiple(
    List<XFile> files, {
    int quality = 80,
    int? minWidth,
    int? minHeight,
    int? maxWidth,
    int? maxHeight,
    bool keepExif = false,
    CompressFormat format = CompressFormat.jpeg,
    Function(int current, int total)? onProgress,
  }) async {
    final compressedFiles = <XFile>[];
    
    for (int i = 0; i < files.length; i++) {
      onProgress?.call(i + 1, files.length);
      
      final compressed = await compressFile(
        files[i].path,
        quality: quality,
        minWidth: minWidth,
        minHeight: minHeight,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        keepExif: keepExif,
        format: format,
      );
      
      if (compressed != null) {
        compressedFiles.add(compressed);
      } else {
        compressedFiles.add(files[i]); // 如果压缩失败，使用原文件
      }
    }
    
    return compressedFiles;
  }
}

/// 图片查看器组件
/// 封装photo_view，提供统一的图片预览体验
class ImageViewer extends StatefulWidget {
  const ImageViewer({
    super.key,
    required this.images,
    this.initialIndex = 0,
    this.backgroundColor,
    this.enableRotation = true,
    this.heroAttributes,
    this.onPageChanged,
    this.loadingBuilder,
    this.errorBuilder,
    this.enableSwipeToExit = true,
  });

  final List<String> images;
  final int initialIndex;
  final Color? backgroundColor;
  final bool enableRotation;
  final PhotoViewHeroAttributes? heroAttributes;
  final void Function(int index)? onPageChanged;
  final Widget Function(BuildContext context, ImageChunkEvent? event)? loadingBuilder;
  final Widget Function(BuildContext context, Object error, StackTrace? stackTrace)? errorBuilder;
  final bool enableSwipeToExit;

  @override
  State<ImageViewer> createState() => _ImageViewerState();
}

class _ImageViewerState extends State<ImageViewer> {
  late PageController _pageController;
  late int _currentIndex;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget.backgroundColor ?? Theme.of(context).colorScheme.scrim,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          '${_currentIndex + 1} / ${widget.images.length}',
          style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
        ),
        iconTheme: IconThemeData(color: Theme.of(context).colorScheme.onSurface),
        actions: [
          if (widget.enableSwipeToExit)
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () => Navigator.pop(context),
            ),
        ],
      ),
      body: PhotoViewGallery.builder(
        pageController: _pageController,
        itemCount: widget.images.length,
        builder: (context, index) {
          return PhotoViewGalleryPageOptions.customChild(
            child: _buildImage(widget.images[index]),
            initialScale: PhotoViewComputedScale.contained,
            minScale: PhotoViewComputedScale.contained * 0.8,
            maxScale: PhotoViewComputedScale.covered * 2.0,
            heroAttributes: widget.heroAttributes,
            disableGestures: !widget.enableRotation,
          );
        },
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
          widget.onPageChanged?.call(index);
        },
        backgroundDecoration: BoxDecoration(
          color: widget.backgroundColor,
        ),
        enableRotation: widget.enableRotation,
      ),
      bottomNavigationBar: widget.images.length > 1
          ? Container(
              color: Theme.of(context).colorScheme.scrim.withOpacity(0.8),
              child: SafeArea(
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                        icon: Icon(Icons.arrow_back_ios, color: Theme.of(context).colorScheme.onSurface),
                        onPressed: _currentIndex > 0
                            ? () => _pageController.previousPage(
                                  duration: const Duration(milliseconds: 300),
                                  curve: Curves.easeInOut,
                                )
                            : null,
                      ),
                      IconButton(
                        icon: Icon(Icons.arrow_forward_ios, color: Theme.of(context).colorScheme.onSurface),
                        onPressed: _currentIndex < widget.images.length - 1
                            ? () => _pageController.nextPage(
                                  duration: const Duration(milliseconds: 300),
                                  curve: Curves.easeInOut,
                                )
                            : null,
                      ),
                    ],
                  ),
                ),
              ),
            )
          : null,
    );
  }

  Widget _buildImage(String imageUrl) {
    return AdvancedImage(
      imageUrl: imageUrl,
      fit: BoxFit.contain,
      placeholder: widget.loadingBuilder?.call(context, null) ??
          Center(
            child: CircularProgressIndicator(color: Theme.of(context).colorScheme.primary),
          ),
      errorWidget: widget.errorBuilder?.call(context, 'Failed to load image', null) ??
          Center(
            child: Icon(
              Icons.broken_image,
              color: Theme.of(context).colorScheme.onSurfaceVariant,
              size: 64,
            ),
          ),
    );
  }

  /// 显示图片查看器
  static Future<void> show(
    BuildContext context, {
    required List<String> images,
    int initialIndex = 0,
    Color? backgroundColor,
    bool enableRotation = true,
    PhotoViewHeroAttributes? heroAttributes,
    void Function(int index)? onPageChanged,
    Widget Function(BuildContext context, ImageChunkEvent? event)? loadingBuilder,
    Widget Function(BuildContext context, Object error, StackTrace? stackTrace)? errorBuilder,
  }) async {
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ImageViewer(
          images: images,
          initialIndex: initialIndex,
          backgroundColor: backgroundColor,
          enableRotation: enableRotation,
          heroAttributes: heroAttributes,
          onPageChanged: onPageChanged,
          loadingBuilder: loadingBuilder,
          errorBuilder: errorBuilder,
        ),
      ),
    );
  }
}

/// 图片选择器组件
/// 提供完整的图片选择、裁剪、压缩流程
class ImagePickerWidget extends StatefulWidget {
  const ImagePickerWidget({
    super.key,
    required this.onImagesSelected,
    this.maxImages = 9,
    this.enableCrop = true,
    this.enableCompress = true,
    this.imageQuality = 80,
    this.maxWidth = 1920,
    this.maxHeight = 1920,
    this.aspectRatio,
    this.cropStyle = CropStyle.rectangle,
    this.selectedImages = const [],
  });

  final Function(List<XFile> images) onImagesSelected;
  final int maxImages;
  final bool enableCrop;
  final bool enableCompress;
  final int imageQuality;
  final int maxWidth;
  final int maxHeight;
  final CropAspectRatio? aspectRatio;
  final CropStyle cropStyle;
  final List<XFile> selectedImages;

  @override
  State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
}

class _ImagePickerWidgetState extends State<ImagePickerWidget> {
  List<XFile> _selectedImages = [];

  @override
  void initState() {
    super.initState();
    _selectedImages = List.from(widget.selectedImages);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (_selectedImages.isNotEmpty)
          Container(
            height: 100,
            margin: const EdgeInsets.only(bottom: 16),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _selectedImages.length + (_selectedImages.length < widget.maxImages ? 1 : 0),
              itemBuilder: (context, index) {
                if (index == _selectedImages.length) {
                  return _buildAddButton();
                }
                return _buildImageItem(_selectedImages[index], index);
              },
            ),
          )
        else
          _buildEmptyState(),
      ],
    );
  }

  Widget _buildAddButton() {
    return GestureDetector(
      onTap: _showImagePicker,
      child: Container(
        width: 80,
        height: 80,
        margin: const EdgeInsets.only(right: 8),
        decoration: BoxDecoration(
          border: Border.all(
            color: Theme.of(context).colorScheme.outline,
            style: BorderStyle.solid,
            width: 2,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(
          Icons.add,
          color: Theme.of(context).colorScheme.onSurfaceVariant,
          size: 32,
        ),
      ),
    );
  }

  Widget _buildImageItem(XFile image, int index) {
    return Container(
      width: 80,
      height: 80,
      margin: const EdgeInsets.only(right: 8),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.file(
              File(image.path),
              width: 80,
              height: 80,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            top: 4,
            right: 4,
            child: GestureDetector(
              onTap: () => _removeImage(index),
              child: Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.error,
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.close,
                  color: Theme.of(context).colorScheme.onError,
                  size: 12,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return GestureDetector(
      onTap: _showImagePicker,
      child: Container(
        height: 100,
        width: double.infinity,
        decoration: BoxDecoration(
          border: Border.all(
            color: Theme.of(context).colorScheme.outline,
            style: BorderStyle.solid,
            width: 2,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.image,
              color: Theme.of(context).colorScheme.onSurfaceVariant,
              size: 32,
            ),
            const SizedBox(height: 8),
            Text(
              '点击添加图片',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showImagePicker() async {
    if (_selectedImages.length >= widget.maxImages) {
      SmartDialogs.showWarning(message: '最多只能选择${widget.maxImages}张图片');
      return;
    }

    final remainingSlots = widget.maxImages - _selectedImages.length;
    List<XFile>? newImages;

    if (remainingSlots == 1) {
      // 选择单张图片
      final image = await ImagePickerService.showImagePickerSheet(
        context,
        maxWidth: widget.maxWidth.toDouble(),
        maxHeight: widget.maxHeight.toDouble(),
        imageQuality: widget.imageQuality,
        enableCrop: widget.enableCrop,
      );
      if (image != null) {
        newImages = [image];
      }
    } else {
      // 选择多张图片
      final images = await ImagePickerService.pickMultipleImages(
        maxWidth: widget.maxWidth.toDouble(),
        maxHeight: widget.maxHeight.toDouble(),
        imageQuality: widget.imageQuality,
        limit: remainingSlots,
      );
      if (images != null && images.isNotEmpty) {
        newImages = images;
      }
    }

    if (newImages != null && newImages.isNotEmpty) {
      // 压缩图片（如果启用）
      if (widget.enableCompress) {
        SmartDialogs.showLoading(message: '正在处理图片...');
        try {
          newImages = await ImageCompressService.compressMultiple(
            newImages,
            quality: widget.imageQuality,
            maxWidth: widget.maxWidth,
            maxHeight: widget.maxHeight,
          );
        } finally {
          SmartDialogs.dismiss();
        }
      }

      setState(() {
        _selectedImages.addAll(newImages!);
      });
      
      widget.onImagesSelected(_selectedImages);
    }
  }

  void _removeImage(int index) {
    setState(() {
      _selectedImages.removeAt(index);
    });
    widget.onImagesSelected(_selectedImages);
  }
}